import { Inject, Injectable } from '@nestjs/common';
import { CreateLabelDto } from './dto/create-label.dto';
import { UpdateLabelDto } from './dto/update-label.dto';
import { QueryDto } from './dto/query.dto';
import { Label } from './entities/label.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Like, Repository } from 'typeorm';

@Injectable()
export class LabelsService {
  constructor(
    @InjectRepository(Label) 
    private labelRepository: Repository<Label>
  ) {}

  async create(createLabelDto: CreateLabelDto) {
    // 校验
    const exit = await this.labelRepository.findOneBy({name:createLabelDto.name,label:createLabelDto.label});

    if(exit){
      return {
        code: 400,
        data: null,
        message: '标签已存在'
      }
    }
    
    const lable = await this.labelRepository.create(createLabelDto);
    return await this.labelRepository.save(lable);
  }

  async findAll(queryDto: QueryDto) {
    const {pageNum=1,pageSize=10,...rest} = queryDto

    const [rows,total] = await this.labelRepository.findAndCount({
      skip: (pageNum - 1) * pageSize,
      take: pageSize,
      where: {
        type: rest.type,
        label: rest.label && Like(`%${rest.label}%`),
        name: rest.name && Like(`%${rest.name}%`)
      }
    })

    return {
        rows,
        total
    }
  }

  findOne(id: number) {
    return this.labelRepository.findOneBy({id});
  }

  update(id: number, updateLabelDto: UpdateLabelDto) {
    return this.labelRepository.update(id,updateLabelDto);
  }

  remove(id: number) {
    return this.labelRepository.delete(id);
  }
}
